package org.example.service;

import cn.hutool.core.lang.Snowflake;
import org.example.dao.BookDao;
import org.example.dao.OrderDao;
import org.example.entity.Order;
import org.example.mq.SendImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService {
    @Autowired
    private SendImpl send;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private BookDao bookDao;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void createOrder(Order order){
        order.setStatus(0);
        if(order.getOrderId() == null){
            order.setOrderId(snowflake.nextIdStr());
        }
        order.setCrateTime(new Date());
        order.setUserId(1);
        if(order.getMoney() == null){
            order.setMoney(bookDao.findById(order.getBookId()).get().getMoney());
        }
        orderDao.save(order);

    }

    public void asynCreateOrder(Order order) {
        order.setOrderId(snowflake.nextIdStr());
        send.sendCreateOrderMessage(null, order);
    }

    public boolean secondsKill(Long bookId, Integer userId) {
        DefaultRedisScript<String> redisScript = new DefaultRedisScript();
        //设置lua脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("stock_simple.lua")));
        redisScript.setResultType(String.class);
        List<String> keys = new ArrayList<>();
        keys.add(BookServiceImpl.SK_BOOK_KEY);
        StringRedisSerializer serializer = new StringRedisSerializer();
        //执行脚本
        String res=stringRedisTemplate.execute(redisScript,serializer,serializer,keys,bookId.toString());
        //秒杀库存已经用完，直接告诉客户秒杀失败
        if(!"1".equals(res)){
            return false;
        }
        //生成订单
        Order order= new Order();
        order.setBookId(bookId);
        order.setUserId(userId);
        asynCreateOrder(order);
        return true;
    }
}
